﻿using Microsoft.Extensions.Logging;
using SqlSugar;
using NetMicro.Domains.Strategy;

namespace NetMicro.Domains
{
    /// <summary>
    /// 上下文基类
    /// </summary>
    public abstract class DbContext
    {

        /// <summary>
        /// 数据库配置
        /// </summary>
        public DbOptions Options { get; set; }

        /// <summary>
        /// 获取分库数据库
        /// </summary>
        public ISubDatabaseDbConfig SubDatabaseDbConfig { get; }


        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="options"></param>
        /// <param name="dbConfig"></param>
        /// <param name="loggerFactory"></param>
        protected DbContext(DbOptions options, ISubDatabaseDbConfig dbConfig)
        {
            if (options != null)
            {
                Options = options;
                ConnectionConfig = new ConnectionConfig()
                {
                    ConnectionString = options.ConnectionString,
                    DbType = options.DbType,
                    IsAutoCloseConnection = true,
                    SlaveConnectionConfigs = options.SlaveConnectionConfigs,
                    ConfigId = options.DbName,
                    InitKeyType = InitKeyType.Attribute,
                    AopEvents = options.AopEvents
                };


            }
            SubDatabaseDbConfig = dbConfig;
        }

        /// <summary>
        /// 连接字符串
        /// </summary>
        protected ConnectionConfig ConnectionConfig { get; }

        /// <summary>
        /// 获取db
        /// </summary>
        public virtual SqlSugarClient Db()
        {
            var config = SubDatabaseDbConfig?.GetConnectionConfig();
            if (config != null)
            {
                return new SqlSugarClient(config);
            }

            return new SqlSugarClient(ConnectionConfig);
        }

    }
}
